<template>
    <div class="page-wrap">
        <div class="controlBtn">
            <WarningTip
                v-if="!disabled && showSave"
                :width="300"
                placement="left"
                content="保存科研前请确认科研环境已配置完毕，保存科研将替换科研模板信息"
            ></WarningTip>
            <!-- 和接入机器 -->
            <Poptip
                confirm
                title="确定要保存科研吗？"
                @on-ok="repAndCreateTip"
                v-if="!disabled && showSave"
                transfer
            >
                <Button type="primary" :disabled="disabled">保存科研</Button>
            </Poptip>
            <!-- <span style="color:#f90" v-if="!disabled">
                <Icon
                    type="ios-information-circle"
                />保存课件前请确认课件环境和接入机器已配置完毕</span
            > -->
            <template v-if="showList">
                <!-- replaceTotal > 0 -->
                <!-- <h3 style="margin: 20px 0px;">替换模板记录列表</h3> -->
                <!-- <TableList
                    ref="selection"
                    :columns="replaceCol"
                    :data="replaceList"
                    :total="replaceTotal"
                    :page="queryReplaceInfo.pageIndex"
                    :size="queryReplaceInfo.pageSize"
                    @change-page="changePage"
                ></TableList> -->
                <TableList :columns="replaceCol" :data="replaceList"></TableList>
            </template>
        </div>
        <Modal
            v-model="loading"
            title="保存科研"
            width="400px"
            :mask-closable="false"
            :closable="false"
            footer-hide
        >
            <h3>
                <Icon
                    type="ios-loading"
                    size="24"
                    class="demo-spin-icon-load"
                    style="margin-right:24px;"
                ></Icon
                >{{ distriTip }}
            </h3>
            <Alert type="warning" show-icon style="margin-top:10px;">请勿离开此页面！！</Alert>
        </Modal>
    </div>
</template>
<script>
//  import encryption from '@/libs/encryption.js'
// import cardList from '@/components/list-template/card-list/cardList.vue';
import {
    repAndCreateTemplate,
    getRepTemplateList,
    getProjectInfo,
    clearDeloyPro,
    experimentDetail
} from '@/api/selfStudy/courseExp.js';
export default {
    // components: { cardList },
    props: {
        showSave: {
            type: Boolean,
            default: false
        },
        showList: {
            type: Boolean,
            default: false
        }
    },
    // props: ['disabled', 'accessName'],
    inject: ['detailParent'],
    data() {
        return {
            loading: false,
            distriTip: '',
            replaceList: [],
            replaceTotal: 0,
            replaceCol: [
                {
                    title: '新模板名称',
                    key: 'newTemplName',
                    placement: 'top-left'
                },
                {
                    title: '原模板名称',
                    key: 'templName'
                },
                {
                    type: 'showTime',
                    title: '替换时间',
                    key: 'createTime'
                }
            ],
            queryReplaceInfo: {
                pageIndex: 1,
                pageSize: 10000,
                ecId: this.ecId
            },
            timeout: 0,
            hasProject: true, //工程是否存在
            curDeployStatus: 0
        };
    },
    computed: {
        accessName() {
            return this.detailParent.contentDetail.accessName;
        },
        prjId() {
            return this.detailParent.contentDetail.projectId;
        },
        ecId() {
            return this.detailParent.contentDetail.id;
        },
        ecName() {
            return this.detailParent.contentDetail.name;
        },
        envTemplateId() {
            return this.detailParent.contentDetail.tmplId;
        },
        deployStatus() {
            return this.detailParent.contentDetail.deployStatus;
        },
        generateImageList() {
            return this.detailParent.contentDetail.generateImageList;
        },
        disabled() {
            return !this.generateImageList || this.generateImageList.length === 0; // || !this.accessName;
        }
    },
    created() {
        // 获取用户id
        this.USER_ID = this.$store.state.user.userId;
        //this.userName = this.$store.state.user.username
    },
    mounted() {
        this.getRepTemplateList();
        this.getProjectInfo();
    },
    beforeRouteLeave(to, from, next) {},
    watch: {
        prjId(val) {
            if (val) {
                this.hasProject = true;
                this.getProjectInfo();
            } else {
                this.hasProject = false;
            }
        }
    },
    methods: {
        repAndCreateTip() {
            // if (!this.accessName) {
            //     this.$Message.info('默认接入机器没有设置');
            //     return;
            // }
            this.getProjectInfo().then((data) => {
                if (this.canClear()) {
                    //工程未清空
                    this.clearDeploy();
                } else {
                    this.repAndCreate();
                }
            });
        },
        repAndCreate() {
            this.loading = true;
            this.distriTip = '正在保存科研...';
            let data = {
                ecId: this.ecId,
                ecName: this.ecName,
                projectId: this.prjId,
                templId: this.envTemplateId
            };
            repAndCreateTemplate(data)
                .then((data) => {
                    if (data.code == 1) {
                        this.getRepTemplateList();
                        this.$emit('getExperStatus');
                        // this.$Message.info(data.message);
                        this.$Message.info({
                            content: data.message,
                            duration: 5
                        });
                    } else {
                        this.$Message.error(data.message);
                    }
                    this.loading = false;
                })
                .catch((error) => {
                    console.log(error);
                    this.loading = false;
                });
        },
        getRepTemplateList() {
            let params = {
                ...this.queryReplaceInfo,
                ecId: this.ecId
            };
            getRepTemplateList(params)
                .then((data) => {
                    if (data.code == 1) {
                        this.replaceList = data.data.items;
                        this.replaceTotal = data.data.total;
                        this.detailParent.updateDetail({ replaceTotal: data.data.total });
                        // if (this.replaceTotal > 0) {
                        //     this.detailParent.updateDetail({
                        //         tmplId: this.replaceList[0].id,
                        //         tmplName: this.replaceList[0].name
                        //     });
                        // }
                    } else {
                        this.$Message.error(data.message);
                    }
                })
                .catch((error) => {
                    console.log(error);
                });
        },
        changePage(page) {
            this.queryReplaceInfo.pageIndex = page;
            this.getRepTemplateList();
        },
        canClear() {
            return (
                this.deployStatus == 3 ||
                this.deployStatus == 6 ||
                this.deployStatus == 8 ||
                this.deployStatus == 14
            );
        },
        clearDeploy() {
            this.loading = true;
            this.distriTip = '正在清空工程';
            let params = {
                projectId: this.prjId
            };
            clearDeloyPro(this.prjId, params)
                .then((res) => {
                    if (res.code === 1 || res.code === 3) {
                        this.getExperStatus();
                    } else {
                        this.loading = false;
                        this.$Message.error({
                            content: res.message,
                            duration: 3
                        });
                    }
                })
                .catch((err) => {
                    console.log(err);
                    this.loading = false;
                    this.$Message.error('服务器连接失败！');
                });
        },
        getProjectInfo() {
            if (!this.prjId) {
                return;
            }
            return new Promise((resolve, reject) => {
                getProjectInfo(this.prjId)
                    .then((data) => {
                        if (data.code == -2) {
                            this.hasProject = false;
                            this.curDeployStatus = 10;
                        } else {
                            this.hasProject = true;
                            let { status, statusCHName } = data.data.project;
                            this.curDeployStatus = status;
                            this.statusCHName = statusCHName;
                        }
                        this.detailParent.updateDetail({
                            deployStatus: this.curDeployStatus,
                            statusCHName: this.statusCHName
                        });
                        resolve(this.curDeployStatus);
                    })
                    .catch((error) => {
                        reject(error);
                    });
            });
        },
        async getExperStatus() {
            clearTimeout(this.timeout);
            let deployStatus = await this.getProjectInfo().catch((err) => {
                console.log(err);
                this.loading = false;
            });
            if (deployStatus == 0 || deployStatus == 14) {
                if (deployStatus == 0) {
                    this.repAndCreate(); //清空之后执行报存
                } else {
                    this.loading = false;
                }
            } else {
                this.timeout = setTimeout(() => {
                    this.getExperStatus();
                }, 2000);
            }
        }
    }
};
</script>
<style scoped>
.demo-spin-icon-load {
    animation: ani-demo-spin 1s linear infinite;
}

@keyframes ani-demo-spin {
    from {
        transform: rotate(0deg);
    }
    50% {
        transform: rotate(180deg);
    }
    to {
        transform: rotate(360deg);
    }
}
</style>
